package com.sitech.ibnms.c3p.quartz;

import com.sitech.ibnms.c3p.Application;
import com.sitech.ibnms.c3p.task.C3pTaskFlowServiceExtends;
import com.sitech.ibnms.c3p.util.C3pConstants;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.ignite.Ignite;
import org.apache.ignite.lang.IgniteRunnable;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于启动C3pTask的Job
 * Created by liujhc on 7/23.
 * 自动 周期性 任务 触发  quartz表自动触发 的任务
 */
public class StartC3pTaskJob implements Job {
    private Logger logger = LoggerFactory.getLogger(StartC3pTaskJob.class);
    public static final String C3P_TASK_ID = "C3P_TASK_ID";
    public static final String USER_ID = "USER_ID";
    public static final String TASK_TITLE = "TASK_TITLE";
    @Autowired
    private Ignite ignite;

    @Override
    public void execute(final JobExecutionContext context) throws JobExecutionException {
        ignite.compute().run(new IgniteRunnable() {
            @Override
            public void run() {
                try {
                    logger.debug("execute c3p task starting job [fireInstanceId={}, triggerName={}, fireTime={}, scheduledFireTime={}, " +
                                    "previousFireTime={}, nextFireTime={}, mergedJobDataMap={}]",
                            context.getFireInstanceId(),
                            context.getTrigger().getKey().getName(),
                            format(context.getFireTime()),
                            format(context.getScheduledFireTime()),
                            format(context.getPreviousFireTime()),
                            format(context.getNextFireTime()),
                            context.getMergedJobDataMap().getWrappedMap()
                    );
                    Map<String, Object> jobDataMap = context.getMergedJobDataMap().getWrappedMap();
                    String c3pTaskId = (String) jobDataMap.get(C3P_TASK_ID);
                    String userId = (String) jobDataMap.get(USER_ID);
                    String taskTitle = (String) jobDataMap.get(TASK_TITLE);

                    Map<String, String> param = new HashMap<String, String>();
                    param.put(C3pConstants.CONTEXT_SCHEDULE_ID, context.getTrigger().getKey().getName());
                    JobExecutionContext jobExecutionContext = (JobExecutionContext) jobDataMap.get(C3pConstants.JOB_EXECUTION_CONTEXT);
                    if (jobExecutionContext == null) {
                        jobExecutionContext = context;
                    }
                    param.putAll(toMap(jobExecutionContext));

                    Application.getBean(C3pTaskFlowServiceExtends.class).startTask(c3pTaskId, userId, taskTitle, param);
                } catch (Throwable t) {
                    logger.error(t.getMessage(), t);
                }
            }
        });

    }

    private Map<String, String> toMap(JobExecutionContext context) {
        Map<String, String> contextMap = new HashMap<String, String>();
        contextMap.put(C3pConstants.JOB_EXECUTION_CONTEXT + ".fireInstanceId", context.getFireInstanceId());
        contextMap.put(C3pConstants.JOB_EXECUTION_CONTEXT + ".triggerName", context.getTrigger().getKey().getName());
        contextMap.put(C3pConstants.JOB_EXECUTION_CONTEXT + ".fireTime", format(context.getFireTime()));
        contextMap.put(C3pConstants.JOB_EXECUTION_CONTEXT + ".scheduledFireTime", format(context.getScheduledFireTime()));
        contextMap.put(C3pConstants.JOB_EXECUTION_CONTEXT + ".previousFireTime", format(context.getPreviousFireTime()));
        contextMap.put(C3pConstants.JOB_EXECUTION_CONTEXT + ".nextFireTime", format(context.getNextFireTime()));
        return contextMap;
    }

    public String format(Date date) {
        return date == null ? null : DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
    }
}
